// Vue应用主文件
const { createApp } = Vue;

// 树形选择选项组件
const TreeSelectOption = {
    name: 'TreeSelectOption',
    template: '#tree-select-option-template',
    props: {
        option: {
            type: Object,
            required: true
        },
        selectedValue: {
            type: [String, Number],
            default: null
        },
        level: {
            type: Number,
            default: 0
        },
        expandedOptions: {
            type: Set,
            default: () => new Set()
        }
    },
    emits: ['select', 'toggle'],
    computed: {
        isExpanded() {
            return this.expandedOptions.has(this.option.id);
        }
    },
    methods: {
        toggleExpanded() {
            this.$emit('toggle', this.option.id);
        },
        selectOption(value) {
            this.$emit('select', value);
        }
    }
};

// 树形选择组件
const TreeSelect = {
    name: 'TreeSelect',
    template: '#tree-select-template',
    components: {
        TreeSelectOption
    },
    props: {
        modelValue: {
            type: [String, Number],
            default: null
        },
        options: {
            type: Array,
            default: () => []
        },
        placeholder: {
            type: String,
            default: '请选择'
        },
        clearable: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:modelValue', 'update:model-value'],
    data() {
        return {
            isOpen: false,
            expandedOptions: new Set()
        };
    },
    computed: {
        displayValue() {
            if (!this.modelValue) return '';
            const option = this.findOptionById(this.options, this.modelValue);
            if (!option) return '';

            // 始终优先显示完整路径，若无路径则回退到名称
            return option.path || option.name || '';
        }
    },
    methods: {
        toggleDropdown() {
            this.isOpen = !this.isOpen;

            // 打开时自动展开已选中项的路径
            if (this.isOpen && this.modelValue) {
                this.expandPathToOption(this.modelValue);
            }
        },
        selectOption(optionId) {
            this.$emit('update:modelValue', optionId);
            this.$emit('update:model-value', optionId);
            this.isOpen = false;
        },
        clearValue() {
            this.$emit('update:modelValue', null);
            this.$emit('update:model-value', null);
        },
        toggleOption(optionId) {
            if (this.expandedOptions.has(optionId)) {
                this.expandedOptions.delete(optionId);
            } else {
                this.expandedOptions.add(optionId);
            }
        },
        findOptionById(options, id) {
            for (const option of options) {
                if (option.id === id) return option;
                if (option.children && option.children.length > 0) {
                    const found = this.findOptionById(option.children, id);
                    if (found) return found;
                }
            }
            return null;
        },
        expandPathToOption(targetId) {
            const path = this.findPathToOption(this.options, targetId, []);
            if (path.length > 0) {
                // 展开路径上的所有父级
                for (let i = 0; i < path.length - 1; i++) {
                    this.expandedOptions.add(path[i].id);
                }
            }
        },
        findPathToOption(options, targetId, currentPath) {
            for (const option of options) {
                const newPath = [...currentPath, option];

                if (option.id === targetId) {
                    return newPath;
                }

                if (option.children && option.children.length > 0) {
                    const found = this.findPathToOption(option.children, targetId, newPath);
                    if (found.length > 0) {
                        return found;
                    }
                }
            }
            return [];
        }
    },
    mounted() {
        // 点击外部关闭下拉框
        document.addEventListener('click', (e) => {
            if (!this.$el.contains(e.target)) {
                this.isOpen = false;
            }
        });
    }
};

// 首页分类节点组件
const HomeCategoryNode = {
    name: 'HomeCategoryNode',
    template: '#home-category-node-template',
    props: {
        category: {
            type: Object,
            required: true
        },
        bookmarks: {
            type: Array,
            default: () => []
        }
    },
    emits: ['view-category', 'visit-bookmark'],
    methods: {
        getCategoryBookmarksAsync(categoryId) {
            return this.bookmarks.filter(bookmark => bookmark.category_id === categoryId);
        }
    }
};

// 分类树节点组件
const CategoryTreeNode = {
    name: 'CategoryTreeNode',
    template: '#category-tree-node-template',
    props: {
        category: {
            type: Object,
            required: true
        },
        expandedCategories: {
            type: Set,
            required: true
        }
    },
    emits: ['toggle', 'edit', 'delete'],
    inject: ['getBookmarkCount'],
    methods: {
        // 本地方法可以在这里添加
    }
};

// 分类管理递归节点组件
const CategoryManagementNode = {
    name: 'CategoryManagementNode',
    template: '#category-management-node-template',
    props: {
        category: {
            type: Object,
            required: true
        },
        level: {
            type: Number,
            default: 1
        },
        expandedCategories: {
            type: Array,
            default: () => []
        },
        showExpanded: {
            type: Boolean,
            default: true
        }
    },
    emits: ['handle-category-click', 'edit-category', 'delete-category', 'get-category-bookmark-count', 'format-date', 'toggle-category-bookmarks'],
    methods: {
        getTitleTag(level) {
            if (level === 1) return 'h5';
            if (level === 2) return 'h6';
            return 'span';
        },
        getBookmarkCount(categoryId) {
            // 通过根组件获取收藏数量
            let parent = this.$parent;
            while (parent && !parent.getCategoryBookmarkCount) {
                parent = parent.$parent;
            }
            return parent ? parent.getCategoryBookmarkCount(categoryId) : 0;
        },
        formatCategoryDate(dateString) {
            // 通过根组件格式化日期
            let parent = this.$parent;
            while (parent && !parent.formatDate) {
                parent = parent.$parent;
            }
            return parent ? parent.formatDate(dateString) : dateString;
        }
    }
};

// Vue应用配置
const vueAppConfig = {
    data() {
        return {
            // 当前页面
            currentPage: 'login',
            // 当前标签页
            activeTab: 'home',
            // 加载状态
            isLoading: false,
            // 用户信息
            user: {
                id: null,
                username: '',
                email: ''
            },
            // 登录表单
            loginForm: {
                username: '',
                password: ''
            },
            // 注册表单
            registerForm: {
                username: '',
                email: '',
                password: ''
            },
            // 分类数据（平铺列表，用于下拉选择等）
            categories: [],
            // 分类树数据（树形结构，用于分类管理页面）
            categoryTree: [],
            // 收藏数据
            bookmarks: [],
            // 消息提示
            message: {
                show: false,
                text: '',
                type: 'info'
            },
            // 欢迎弹窗
            showWelcomeModal: false,
            // 创建分类弹窗
            showCreateCategoryModal: false,
            // 创建收藏弹窗
            showCreateBookmarkModal: false,
            // 编辑分类弹窗
            showEditCategoryModal: false,
            // 编辑收藏弹窗
            showEditBookmarkModal: false,
            // 分类表单
            categoryForm: {
                name: '',
                parent_id: '',
                description: ''
            },
            // 收藏表单
            bookmarkForm: {
                url: '',
                title: '',
                description: '',
                category_id: ''
            },
            // 编辑分类表单
            editCategoryForm: {
                id: null,
                name: '',
                parent_id: '',
                description: ''
            },
            // 编辑收藏表单
            editBookmarkForm: {
                id: null,
                url: '',
                title: '',
                description: '',
                category_id: ''
            },
            // 搜索和筛选
            searchQuery: '',
            filterCategory: '',
            // 侧边栏状态
            hoveredTab: null,

            // 分类树相关
            categoryTree: [],
            expandedCategories: [], // 展开的分类ID列表（用于子分类的子分类）
            rootCategoriesExpanded: [], // 展开的根分类ID列表

            // 分类收藏页面
            categoryBookmarks: [],
            currentCategoryPath: '',
            currentCategoryId: null,
            // 编辑个人信息弹窗
            showEditProfileModal: false,
            // 编辑个人信息表单
            editProfileForm: {
                username: '',
                email: '',
                password: ''
            },
            // 最近活动
            recentActivities: [],

            // 批量操作相关
            batchMode: false, // 是否处于批量操作模式
            selectedBookmarks: [], // 选中的收藏ID列表
            showBatchMoveModal: false, // 批量移动弹窗
            batchMoveForm: {
                target_category_id: ''
            },

        };
    },

    async mounted() {
        // 确保侧边栏保持静默状态
        this.ensureSidebarSilent();

        // 检查是否已登录
        this.checkAuthStatus();

        // 监听认证错误事件
        window.addEventListener('auth-error', () => {
            this.handleLogout();
        });

        // 监听消息事件
        window.addEventListener('show-message', (event) => {
            this.showMessage(event.detail.message, event.detail.type, event.detail.duration);
        });
    },

    watch: {
        categories: {
            handler() {
                // 当分类数据变化时重新生成分类树
                this.$nextTick(() => {
                    this.generateCategoryTree();
                });
            },
            deep: true
        },
        categoryTree: {
            handler() {
                // 当分类树数据变化时自动展开顶级分类
                this.$nextTick(() => {
                    this.autoExpandRootCategories();
                });
            },
            deep: true
        },
        activeTab: {
            handler(newTab) {
                // 当切换到分类管理页面时，确保加载分类数据
                if (newTab === 'categories') {
                    console.log('切换到分类管理页面，加载分类数据');
                    this.loadCategories();
                }
                // 当切换到个人信息页面时，加载用户详细信息
                if (newTab === 'profile') {
                    console.log('切换到个人信息页面，加载用户详细信息');
                    this.loadUserProfile();
                }
                // 当切换到收藏管理页面时，加载最新收藏数据
                if (newTab === 'bookmarks') {
                    console.log('切换到收藏管理页面，加载最新收藏数据');
                    this.loadBookmarks();
                }
            }
        }
    },

    methods: {
        // 检查认证状态
        checkAuthStatus() {
            // 确保所有弹窗都关闭，侧边栏保持静默
            this.resetAllModals();

            const token = localStorage.getItem('jwt_token');
            if (token) {
                // 尝试解析token获取用户信息
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    const isExpired = Date.now() > payload.exp * 1000;

                    if (!isExpired) {
                        this.user.id = payload.user_id;
                        this.user.username = payload.username;
                        this.currentPage = 'home';
                        // 静默加载数据，不显示欢迎弹窗
                        this.loadInitialData(false);
                        // 获取完整的用户信息
                        this.loadUserProfileSilently();
                        return;
                    }
                } catch (error) {
                    console.error('Token解析失败:', error);
                }
            }

            // 未登录或token无效，跳转到登录页
            this.currentPage = 'login';
        },

        // 重置所有弹窗状态
        resetAllModals() {
            this.showWelcomeModal = false;
            this.showCreateCategoryModal = false;
            this.showCreateBookmarkModal = false;
            this.showEditCategoryModal = false;
            this.showEditBookmarkModal = false;
            // 确保侧边栏不会自动弹出
            this.hoveredTab = null;
        },

        // 确保侧边栏保持静默状态（防止自动弹出）
        ensureSidebarSilent() {
            this.hoveredTab = null;
        },

        // 加载初始数据
        async loadInitialData(showWelcome = false) {
            try {
                this.isLoading = true;
                // 确保侧边栏保持静默状态
                this.hoveredTab = null;

                // 并行加载分类树和收藏数据
                const [categoryTreeRes, bookmarksRes] = await Promise.all([
                    api.getCategoryTree(),
                    api.getBookmarks()
                ]);

                if (categoryTreeRes.code === 200) {
                    this.categoryTree = categoryTreeRes.data || [];
                    // 同时生成平铺的分类列表用于下拉选择
                    this.categories = this.flattenCategoryTree(this.categoryTree);
                }

                if (bookmarksRes.code === 200) {
                    this.bookmarks = bookmarksRes.data || [];
                }

                // 生成最近活动数据
                this.generateRecentActivities();

                // 只在首次登录时显示欢迎弹窗
                if (showWelcome) {
                    this.showWelcomeModal = true;
                    setTimeout(() => {
                        this.showWelcomeModal = false;
                    }, 3000);
                }

            } catch (error) {
                console.error('加载初始数据失败:', error);
                this.showMessage('加载数据失败', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 处理登录
        async handleLogin() {
            if (!this.loginForm.username || !this.loginForm.password) {
                this.showMessage('请填写完整的登录信息', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.login(this.loginForm);

                if (response.code === 200) {
                    this.user = response.data.user;
                    this.currentPage = 'home';
                    this.showMessage(`欢迎回来，${this.user.username}！`, 'success');

                    // 清空表单
                    this.loginForm = { username: '', password: '' };

                    // 确保侧边栏保持静默状态
                    this.hoveredTab = null;

                    // 加载数据
                    await this.loadInitialData(true);
                } else {
                    this.showMessage(response.message || '登录失败', 'error');
                }
            } catch (error) {
                console.error('登录失败:', error);
                this.showMessage('登录失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 处理注册
        async handleRegister() {
            if (!this.registerForm.username || !this.registerForm.email || !this.registerForm.password) {
                this.showMessage('请填写完整的注册信息', 'warning');
                return;
            }

            if (!utils.validateEmail(this.registerForm.email)) {
                this.showMessage('请输入有效的邮箱地址', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.register(this.registerForm);

                if (response.code === 200) {
                    this.showMessage('注册成功！请登录', 'success');
                    this.goToLogin();
                    // 清空表单
                    this.registerForm = { username: '', email: '', password: '' };
                } else {
                    this.showMessage(response.message || '注册失败', 'error');
                }
            } catch (error) {
                console.error('注册失败:', error);
                this.showMessage('注册失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 处理登出
        handleLogout() {
            api.setToken('');
            this.user = { id: null, username: '', email: '' };
            this.categories = [];
            this.bookmarks = [];
            this.currentPage = 'login';
            this.activeTab = 'home';
            this.showMessage('已安全退出', 'info');
        },

        // 跳转到注册页
        goToRegister() {
            this.currentPage = 'register';
        },

        // 跳转到登录页
        goToLogin() {
            this.currentPage = 'login';
        },

        // 关闭欢迎弹窗
        closeWelcomeModal() {
            this.showWelcomeModal = false;
        },

        // 关闭创建分类模态框
        closeCreateCategoryModal() {
            this.showCreateCategoryModal = false;
            this.categoryForm = { name: '', parent_id: '', description: '' };
        },

        // 关闭创建收藏模态框
        closeCreateBookmarkModal() {
            this.showCreateBookmarkModal = false;
            this.bookmarkForm = { url: '', title: '', description: '', category_id: '' };
        },

        // 打开创建收藏模态框（支持预设分类）
        openCreateBookmarkModal(categoryId = null) {
            this.showCreateBookmarkModal = true;
            if (categoryId) {
                this.bookmarkForm.category_id = categoryId;
            } else if (this.currentCategoryId) {
                // 如果在分类收藏页面，自动选择当前分类
                this.bookmarkForm.category_id = this.currentCategoryId;
            }
        },

        // 关闭编辑分类模态框
        closeEditCategoryModal() {
            this.showEditCategoryModal = false;
            this.editCategoryForm = { id: null, name: '', parent_id: '', description: '' };
        },

        // 关闭编辑收藏模态框
        closeEditBookmarkModal() {
            this.showEditBookmarkModal = false;
            this.editBookmarkForm = { id: null, url: '', title: '', description: '', category_id: '' };
        },

        // 关闭编辑个人信息模态框
        closeEditProfileModal() {
            this.showEditProfileModal = false;
            this.editProfileForm = { username: '', email: '', password: '' };
        },

        // 获取分类路径
        getCategoryPath(category) {
            const path = [];
            let current = category;

            while (current) {
                path.unshift(current.name);
                current = this.categories.find(c => c.id === current.parent_id);
            }

            return path.join('/');
        },

        // 加载分类收藏
        async loadCategoryBookmarks(categoryId) {
            try {
                console.log('正在加载分类收藏，分类ID:', categoryId);
                const response = await api.getBookmarksByCategory(categoryId);
                console.log('API响应:', response);

                if (response.code === 200) {
                    this.categoryBookmarks = response.data || [];
                    console.log('成功加载分类收藏，数量:', this.categoryBookmarks.length);
                } else {
                    console.log('API返回错误:', response.message);
                    this.categoryBookmarks = [];
                }
            } catch (error) {
                console.error('加载分类收藏失败:', error);
                this.categoryBookmarks = [];
            }
        },

        // 生成分类树
        generateCategoryTree() {
            this.treeNodes = [];
            this.treeLines = [];

            const rootCategories = this.categories.filter(c => !c.parent_id);
            const nodeWidth = 180;
            const nodeHeight = 100;
            const levelHeight = 140;

            let nodeId = 0;

            // 递归生成节点
            const generateNodes = (categories, level, parentX, parentY) => {
                const totalWidth = categories.length * nodeWidth;
                const startX = parentX - totalWidth / 2 + nodeWidth / 2;

                categories.forEach((category, index) => {
                    const x = startX + index * nodeWidth;
                    const y = level * levelHeight + 80;

                    const node = {
                        id: nodeId++,
                        category: category,
                        x: x,
                        y: y,
                        isRoot: level === 0
                    };

                    this.treeNodes.push(node);

                    // 如果有父节点，创建连接线
                    if (level > 0) {
                        const line = {
                            id: `line-${category.id}`,
                            path: `M ${parentX} ${parentY + 40} L ${parentX} ${y - 30} L ${x} ${y - 30} L ${x} ${y}`,
                            highlighted: false
                        };
                        this.treeLines.push(line);
                    }

                    // 递归处理子分类
                    const children = this.categories.filter(c => c.parent_id === category.id);
                    if (children.length > 0) {
                        generateNodes(children, level + 1, x, y);
                    }
                });
            };

            // 计算SVG尺寸
            const maxWidth = Math.max(rootCategories.length * nodeWidth + 100, 800);
            const maxDepth = this.getMaxCategoryDepth();
            const maxHeight = Math.max(maxDepth * levelHeight + 200, 500);

            this.treeSvgWidth = maxWidth;
            this.treeSvgHeight = maxHeight;

            // 生成根节点
            if (rootCategories.length > 0) {
                generateNodes(rootCategories, 0, maxWidth / 2, 0);
            }
        },

        // 获取分类最大深度
        getMaxCategoryDepth() {
            let maxDepth = 0;

            const getDepth = (categoryId, currentDepth) => {
                const children = this.categories.filter(c => c.parent_id === categoryId);
                if (children.length === 0) {
                    maxDepth = Math.max(maxDepth, currentDepth);
                    return;
                }

                children.forEach(child => {
                    getDepth(child.id, currentDepth + 1);
                });
            };

            const rootCategories = this.categories.filter(c => !c.parent_id);
            rootCategories.forEach(root => {
                getDepth(root.id, 1);
            });

            return maxDepth;
        },

        // 高亮路径
        highlightPath(categoryId) {
            this.treeLines.forEach(line => {
                line.highlighted = false;
            });

            // 找到从根到当前节点的路径
            const path = this.getPathToRoot(categoryId);
            path.forEach(id => {
                const line = this.treeLines.find(l => l.id === `line-${id}`);
                if (line) {
                    line.highlighted = true;
                }
            });
        },

        // 清除高亮
        clearHighlight() {
            this.treeLines.forEach(line => {
                line.highlighted = false;
            });
        },

        // 获取到根节点的路径
        getPathToRoot(categoryId) {
            const path = [];
            let current = this.categories.find(c => c.id === categoryId);

            while (current && current.parent_id) {
                path.push(current.id);
                current = this.categories.find(c => c.id === current.parent_id);
            }

            return path;
        },

        // 技能树相关方法

        // 检查分类是否有子分类
        hasChildren(categoryId) {
            return this.categories.some(c => c.parent_id === categoryId);
        },

        // 获取技能图标
        getSkillIcon(categoryName) {
            const iconMap = {
                '前端开发': '🎨',
                '后端开发': '⚙️',
                '数据库': '🗄️',
                '工具': '🔧',
                '学习': '📚',
                '娱乐': '🎮',
                '新闻': '📰',
                '购物': '🛒',
                '社交': '👥',
                '音乐': '🎵',
                '视频': '📺',
                '图片': '🖼️',
                '文档': '📄',
                '代码': '💻',
                'JavaScript': '🟨',
                'Python': '🐍',
                'Java': '☕',
                'React': '⚛️',
                'Vue': '💚',
                'Node.js': '🟢',
                'MySQL': '🐬',
                'MongoDB': '🍃',
                'Redis': '🔴',
                'Git': '📦',
                'Docker': '🐳',
                'AWS': '☁️'
            };

            // 根据分类名称匹配图标，如果没有匹配则使用默认图标
            for (const [key, icon] of Object.entries(iconMap)) {
                if (categoryName.toLowerCase().includes(key.toLowerCase())) {
                    return icon;
                }
            }

            return '📁'; // 默认图标
        },

        // 切换技能树展开状态
        toggleSkillTree(category) {
            if (this.expandedCategory === category.id) {
                this.closeSkillTree();
            } else {
                this.expandSkillTree(category);
            }
        },

        // 展开技能树
        expandSkillTree(category) {
            this.expandedCategory = category.id;
            this.generateSkillTree(category);
        },

        // 关闭技能树
        closeSkillTree() {
            this.expandedCategory = null;
            this.expandedSkills = [];
            this.skillConnections = [];
        },

        // 生成技能树
        generateSkillTree(rootCategory) {
            this.expandedSkills = [];
            this.skillConnections = [];

            const children = this.categories.filter(c => c.parent_id === rootCategory.id);
            if (children.length === 0) return;

            const nodeWidth = 120;
            const nodeHeight = 100;
            const startX = 150;
            const startY = 120;
            const spacing = 180;

            // 计算技能树尺寸
            const maxCols = Math.ceil(Math.sqrt(children.length));
            const maxRows = Math.ceil(children.length / maxCols);

            this.skillTreeWidth = Math.max(maxCols * spacing + 300, 900);
            this.skillTreeHeight = Math.max(maxRows * spacing + 250, 500);

            // 生成子技能节点
            children.forEach((child, index) => {
                const col = index % maxCols;
                const row = Math.floor(index / maxCols);

                const x = startX + col * spacing;
                const y = startY + row * spacing;

                const skill = {
                    id: child.id,
                    category: child,
                    x: x,
                    y: y,
                    unlocked: this.getCategoryBookmarkCount(child.id) > 0,
                    active: false
                };

                this.expandedSkills.push(skill);

                // 创建连接线（从根技能到子技能）
                const rootX = this.skillTreeWidth / 2;
                const rootY = 60;

                const connection = {
                    id: `connection-${child.id}`,
                    path: `M ${rootX} ${rootY} Q ${(rootX + x) / 2} ${(rootY + y) / 2} ${x} ${y}`,
                    active: false,
                    unlocked: skill.unlocked
                };

                this.skillConnections.push(connection);
            });
        },

        // 显示技能预览
        showSkillPreview(category) {
            console.log('显示技能预览:', category.name);
        },

        // 隐藏技能预览
        hideSkillPreview() {
            // 隐藏预览
        },

        // 高亮技能路径
        highlightSkillPath(categoryId) {
            this.skillConnections.forEach(conn => {
                conn.active = conn.id === `connection-${categoryId}`;
            });

            this.expandedSkills.forEach(skill => {
                skill.active = skill.category.id === categoryId;
            });
        },

        // 切换分类展开/折叠状态
        toggleCategory(categoryId) {
            const index = this.expandedCategories.indexOf(categoryId);
            if (index > -1) {
                // 如果已展开，则折叠
                this.expandedCategories.splice(index, 1);
            } else {
                // 如果已折叠，则展开
                this.expandedCategories.push(categoryId);
            }
        },

        // 展开所有分类
        expandAllCategories() {
            // 展开所有根分类
            this.autoExpandRootCategories();
            // 展开所有子分类
            this.expandedCategories = [];
            this.collectAllCategoryIds(this.categoryTree);
        },

        // 折叠所有分类
        collapseAllCategories() {
            // 折叠所有根分类
            this.rootCategoriesExpanded = [];
            // 折叠所有子分类
            this.expandedCategories = [];
        },

        // 收集所有分类ID
        collectAllCategoryIds(categories) {
            for (const category of categories) {
                if (category.children && category.children.length > 0) {
                    this.expandedCategories.push(category.id);
                    this.collectAllCategoryIds(category.children);
                }
            }
        },

        // 自动展开顶级分类
        autoExpandRootCategories() {
            this.rootCategoriesExpanded = [];
            console.log('开始自动展开顶级分类，分类树数据:', this.categoryTree);
            // 自动展开所有有子分类的顶级分类
            for (const category of this.categoryTree) {
                if (category.children && category.children.length > 0) {
                    this.rootCategoriesExpanded.push(category.id);
                    console.log(`展开顶级分类: ${category.name} (ID: ${category.id})`);
                }
            }
            console.log('自动展开完成，展开的分类ID:', this.rootCategoriesExpanded);
        },

        // 切换根分类展开/折叠状态
        toggleRootCategory(categoryId) {
            const index = this.rootCategoriesExpanded.indexOf(categoryId);
            if (index > -1) {
                // 如果已展开，则折叠
                this.rootCategoriesExpanded.splice(index, 1);
            } else {
                // 如果已折叠，则展开
                this.rootCategoriesExpanded.push(categoryId);
            }
        },

        // 处理分类点击（用于分类管理页面）
        handleCategoryClick(category) {
            console.log('分类点击:', category.name, '有子分类:', category.children && category.children.length > 0);
            // 如果有子分类，则切换展开/折叠状态
            if (category.children && category.children.length > 0) {
                console.log('切换分类展开状态:', category.id);
                this.toggleCategory(category.id);
                console.log('当前展开的分类:', this.expandedCategories);
            }
            // 如果没有子分类，可以在这里添加其他逻辑，比如显示分类详情
        },

        // 切换技能树展开状态
        toggleSkillTree(category) {
            if (this.expandedCategory === category.id) {
                this.closeSkillTree();
            } else {
                this.expandSkillTree(category);
            }
        },

        // 展开技能树
        expandSkillTree(category) {
            this.expandedCategory = category.id;
            this.generateSkillTree(category);
        },

        // 关闭技能树
        closeSkillTree() {
            this.expandedCategory = null;
            this.expandedSkills = [];
            this.skillConnections = [];
        },

        // 生成技能树
        generateSkillTree(rootCategory) {
            this.expandedSkills = [];
            this.skillConnections = [];

            const children = this.categories.filter(c => c.parent_id === rootCategory.id);
            if (children.length === 0) return;

            const nodeWidth = 120;
            const nodeHeight = 100;
            const startX = 100;
            const startY = 100;
            const spacing = 150;

            // 计算技能树尺寸
            const maxCols = Math.ceil(Math.sqrt(children.length));
            const maxRows = Math.ceil(children.length / maxCols);

            this.skillTreeWidth = Math.max(maxCols * spacing + 200, 800);
            this.skillTreeHeight = Math.max(maxRows * spacing + 200, 400);

            // 生成子技能节点
            children.forEach((child, index) => {
                const col = index % maxCols;
                const row = Math.floor(index / maxCols);

                const x = startX + col * spacing;
                const y = startY + row * spacing;

                const skill = {
                    id: child.id,
                    category: child,
                    x: x,
                    y: y,
                    unlocked: this.getCategoryBookmarkCount(child.id) > 0,
                    active: false
                };

                this.expandedSkills.push(skill);

                // 创建连接线（从根技能到子技能）
                const rootX = this.skillTreeWidth / 2;
                const rootY = 50;

                const connection = {
                    id: `connection-${child.id}`,
                    path: `M ${rootX} ${rootY} Q ${(rootX + x) / 2} ${(rootY + y) / 2} ${x} ${y}`,
                    active: false,
                    unlocked: skill.unlocked
                };

                this.skillConnections.push(connection);
            });
        },

        // 显示技能预览
        showSkillPreview(category) {
            // 可以在这里添加预览逻辑
            console.log('显示技能预览:', category.name);
        },

        // 隐藏技能预览
        hideSkillPreview() {
            // 隐藏预览
        },

        // 高亮技能路径
        highlightSkillPath(categoryId) {
            this.skillConnections.forEach(conn => {
                conn.active = conn.id === `connection-${categoryId}`;
            });

            this.expandedSkills.forEach(skill => {
                skill.active = skill.category.id === categoryId;
            });
        },

        // 清除技能高亮
        clearSkillHighlight() {
            this.skillConnections.forEach(conn => {
                conn.active = false;
            });

            this.expandedSkills.forEach(skill => {
                skill.active = false;
            });
        },

        // 显示消息
        showMessage(text, type = 'info', duration = 3000) {
            this.message = {
                show: true,
                text,
                type
            };

            setTimeout(() => {
                this.message.show = false;
            }, duration);
        },

        // 获取消息图标
        getMessageIcon(type) {
            const icons = {
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-circle',
                warning: 'fas fa-exclamation-triangle',
                info: 'fas fa-info-circle'
            };
            return icons[type] || icons.info;
        },

        // 获取分类下的收藏数量
        getCategoryBookmarkCount(categoryId) {
            return this.bookmarks.filter(bookmark => bookmark.category_id === categoryId).length;
        },

        // 获取分类下的收藏
        getCategoryBookmarks(categoryId) {
            return this.bookmarks.filter(bookmark => bookmark.category_id === categoryId);
        },

        // 查看分类收藏
        async viewCategoryBookmarks(category) {
            try {
                console.log('点击分类:', category);
                console.log('分类ID:', category.id);
                console.log('分类路径:', category.path);

                this.activeTab = 'category-bookmarks';
                this.currentCategoryPath = category.path;
                this.currentCategoryId = category.id;

                console.log('开始加载分类收藏...');
                await this.loadCategoryBookmarks(category.id);
                console.log('分类收藏加载完成，数量:', this.categoryBookmarks.length);

                this.showMessage(`正在查看"${category.path}"分类下的收藏`, 'info');
            } catch (error) {
                console.error('查看分类收藏失败:', error);
                this.showMessage('查看分类收藏失败', 'error');
            }
        },

        // 从首页点击分类跳转到收藏管理页面并筛选该分类
        async viewCategoryBookmarksFromHome(category) {
            try {
                // 切换到收藏管理页面
                this.activeTab = 'bookmarks';
                // 设置分类筛选
                this.filterCategory = category.id;
                // 清空搜索条件
                this.searchQuery = '';

                // 等待DOM更新后滚动到顶部
                this.$nextTick(() => {
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });

                this.showMessage(`正在查看"${category.path}"分类下的收藏`, 'info');
            } catch (error) {
                console.error('查看分类收藏失败:', error);
                this.showMessage('查看分类收藏失败', 'error');
            }
        },

        // 访问收藏
        async visitBookmark(bookmark) {
            try {
                // 记录访问
                await api.visitBookmark(bookmark.id);

                // 打开链接
                window.open(utils.formatURL(bookmark.url), '_blank');

                // 更新本地访问次数
                const localBookmark = this.bookmarks.find(b => b.id === bookmark.id);
                if (localBookmark) {
                    localBookmark.visit_count = (localBookmark.visit_count || 0) + 1;
                }
            } catch (error) {
                console.error('访问收藏失败:', error);
                // 即使记录失败也要打开链接
                window.open(utils.formatURL(bookmark.url), '_blank');
            }
        },

        // 刷新数据
        async refreshData() {
            await this.loadInitialData();
        },

        // 处理创建分类
        async handleCreateCategory() {
            if (!this.categoryForm.name.trim()) {
                this.showMessage('请输入分类名称', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const categoryData = {
                    name: this.categoryForm.name.trim(),
                    parent_id: this.categoryForm.parent_id ? parseInt(this.categoryForm.parent_id) : null,
                    description: this.categoryForm.description.trim()
                };

                const response = await api.createCategory(categoryData);

                if (response.code === 200) {
                    this.showMessage('分类创建成功！', 'success');
                    // 重新加载所有数据以确保首页和分类页面都更新
                    await this.loadInitialData();
                    this.closeCreateCategoryModal();
                } else {
                    this.showMessage(response.message || '创建分类失败', 'error');
                }
            } catch (error) {
                console.error('创建分类失败:', error);
                this.showMessage('创建分类失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 处理创建收藏
        async handleCreateBookmark() {
            if (!this.bookmarkForm.url.trim() || !this.bookmarkForm.title.trim()) {
                this.showMessage('请填写网址和标题', 'warning');
                return;
            }

            if (!utils.validateURL(this.bookmarkForm.url)) {
                this.showMessage('请输入有效的网址', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const bookmarkData = {
                    url: utils.formatURL(this.bookmarkForm.url.trim()),
                    title: this.bookmarkForm.title.trim(),
                    description: this.bookmarkForm.description.trim(),
                    category_id: this.bookmarkForm.category_id ? parseInt(this.bookmarkForm.category_id) : null
                };

                const response = await api.createBookmark(bookmarkData);

                if (response.code === 200) {
                    this.showMessage('收藏添加成功！', 'success');

                    // 根据当前页面选择性地更新数据
                    if (this.activeTab === 'bookmarks') {
                        // 如果在收藏管理页面，只更新收藏数据
                        await this.loadBookmarks();
                    } else {
                        // 其他页面重新加载所有数据以确保首页等页面都更新
                        await this.loadInitialData();
                    }

                    // 如果在分类收藏页面，重新加载当前分类的收藏
                    if (this.activeTab === 'category-bookmarks' && this.currentCategoryId) {
                        await this.loadCategoryBookmarks(this.currentCategoryId);
                    }

                    this.closeCreateBookmarkModal();
                } else {
                    this.showMessage(response.message || '添加收藏失败', 'error');
                }
            } catch (error) {
                console.error('添加收藏失败:', error);
                this.showMessage('添加收藏失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 加载分类（统一使用loadInitialData来确保数据一致性）
        async loadCategories() {
            await this.loadInitialData();
        },

        // 加载最新收藏数据
        async loadBookmarks() {
            try {
                this.isLoading = true;
                console.log('开始加载最新收藏数据');

                const response = await api.getBookmarks();

                if (response.code === 200) {
                    console.log('收藏数据加载成功:', response.data);

                    // 更新收藏数据
                    this.bookmarks = response.data || [];

                    console.log('收藏数据已更新，总数:', this.bookmarks.length);
                } else {
                    console.error('获取收藏数据失败:', response.message);
                    this.showMessage(response.message || '获取收藏数据失败', 'error');
                }
            } catch (error) {
                console.error('加载收藏数据失败:', error);
                this.showMessage('加载收藏数据失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 加载用户详细信息
        async loadUserProfile() {
            if (!this.user.id) {
                console.warn('用户ID不存在，无法加载用户详细信息');
                return;
            }

            try {
                this.isLoading = true;
                console.log('开始加载用户详细信息，用户ID:', this.user.id);

                const response = await api.getUserProfile(this.user.id);

                if (response.code === 200) {
                    console.log('用户详细信息加载成功:', response.data);

                    // 更新用户信息
                    this.user = {
                        ...this.user,
                        ...response.data
                    };

                    console.log('用户信息已更新:', this.user);
                } else {
                    console.error('获取用户详细信息失败:', response.message);
                    this.showMessage(response.message || '获取用户信息失败', 'error');
                }
            } catch (error) {
                console.error('加载用户详细信息失败:', error);
                this.showMessage('加载用户信息失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 静默加载用户详细信息（不显示加载状态和错误消息）
        async loadUserProfileSilently() {
            if (!this.user.id) {
                console.warn('用户ID不存在，无法静默加载用户详细信息');
                return;
            }

            try {
                console.log('静默加载用户详细信息，用户ID:', this.user.id);

                const response = await api.getUserProfile(this.user.id);

                if (response.code === 200) {
                    console.log('用户详细信息静默加载成功:', response.data);

                    // 更新用户信息
                    this.user = {
                        ...this.user,
                        ...response.data
                    };

                    console.log('用户信息已静默更新:', this.user);
                } else {
                    console.warn('静默获取用户详细信息失败:', response.message);
                }
            } catch (error) {
                console.warn('静默加载用户详细信息失败:', error);
            }
        },

        // 编辑个人信息后刷新用户数据
        async refreshUserDataAfterEdit() {
            if (!this.user.id) {
                console.warn('用户ID不存在，无法刷新用户数据');
                return;
            }

            try {
                console.log('编辑后刷新用户数据，用户ID:', this.user.id);

                const response = await api.getUserProfile(this.user.id);

                if (response.code === 200) {
                    console.log('编辑后用户数据刷新成功:', response.data);

                    // 更新用户信息，确保使用最新的后端数据
                    this.user = {
                        ...this.user,
                        ...response.data
                    };

                    console.log('用户信息已更新为最新数据:', this.user);
                } else {
                    console.warn('编辑后刷新用户数据失败:', response.message);
                    // 不显示错误消息给用户，因为编辑操作本身已经成功
                }
            } catch (error) {
                console.warn('编辑后刷新用户数据失败:', error);
                // 不显示错误消息给用户，因为编辑操作本身已经成功
            }
        },

        // 将分类树扁平化为数组
        flattenCategoryTree(tree) {
            const result = [];

            function flatten(categories) {
                for (const category of categories) {
                    result.push({
                        id: category.id,
                        name: category.name,
                        level: category.level,
                        path: category.path,
                        parent_id: category.level > 1 ? findParentId(category.path) : null
                    });

                    if (category.children && category.children.length > 0) {
                        flatten(category.children);
                    }
                }
            }

            function findParentId(path) {
                const pathParts = path.split('/');
                if (pathParts.length <= 1) return null;

                const parentPath = pathParts.slice(0, -1).join('/');
                const parent = result.find(cat => cat.path === parentPath);
                return parent ? parent.id : null;
            }

            flatten(tree);
            return result;
        },

        // 加载收藏
        async loadBookmarks() {
            try {
                const response = await api.getBookmarks();
                if (response.code === 200) {
                    this.bookmarks = response.data || [];
                }
            } catch (error) {
                console.error('加载收藏失败:', error);
            }
        },

        // 处理URL预览
        async handleUrlPreview() {
            if (!this.bookmarkForm.url.trim()) {
                this.showMessage('请先输入网址', 'warning');
                return;
            }

            if (!utils.validateURL(this.bookmarkForm.url)) {
                this.showMessage('请输入有效的网址', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.getURLPreview(this.bookmarkForm.url);

                if (response.code === 200 && response.data) {
                    if (response.data.title) {
                        this.bookmarkForm.title = response.data.title;
                    }
                    if (response.data.description) {
                        this.bookmarkForm.description = response.data.description;
                    }
                    this.showMessage('预览获取成功！', 'success');
                } else {
                    this.showMessage('无法获取网址预览，请手动填写标题', 'warning');
                }
            } catch (error) {
                console.error('获取预览失败:', error);
                this.showMessage('获取预览失败，请手动填写标题', 'warning');
            } finally {
                this.isLoading = false;
            }
        },

        // 格式化日期
        formatDate(date) {
            return utils.formatDate(date);
        },

        // 获取域名
        getDomain(url) {
            return utils.getDomain(url);
        },

        // 获取分类显示名称（与tree-select组件的displayValue逻辑保持一致）
        getCategoryName(categoryId) {
            // 首先从扁平化的categories数组中查找
            let category = this.categories.find(cat => cat.id === categoryId);
            if (category) {
                return this.formatCategoryDisplayName(category);
            }

            // 如果没找到，从分类树中递归查找
            const findInTree = (tree) => {
                for (const cat of tree) {
                    if (cat.id === categoryId) {
                        return cat;
                    }
                    if (cat.children && cat.children.length > 0) {
                        const found = findInTree(cat.children);
                        if (found) return found;
                    }
                }
                return null;
            };

            const foundCategory = findInTree(this.categoryTree);
            if (foundCategory) {
                return this.formatCategoryDisplayName(foundCategory);
            }

            return '未知分类';
        },

        // 格式化分类显示名称（与tree-select组件保持一致）
        formatCategoryDisplayName(category) {
            if (!category) return '';

            // 根据分类层级显示不同格式
            // 判断是否为顶级分类：
            // - level === 1 (明确的层级标识)
            // - path中不包含'/' (路径中没有分隔符)
            const isTopLevel = category.level === 1 ||
                !category.path ||
                category.path.indexOf('/') === -1;

            if (isTopLevel) {
                return category.name; // 顶级分类只显示名称
            } else {
                return category.path; // 子分类显示完整路径
            }
        },

        // 处理图片加载错误
        handleImageError(event) {
            event.target.src = '/web/images/default-favicon.png';
        },

        // 处理搜索
        handleSearch() {
            // 搜索逻辑在计算属性中处理
        },

        // 处理筛选
        handleFilter() {
            // 筛选逻辑在计算属性中处理
        },

        // 编辑分类
        editCategory(category) {
            this.editCategoryForm = {
                id: category.id,
                name: category.name,
                parent_id: category.parent_id || '',
                description: category.description || ''
            };
            this.showEditCategoryModal = true;
        },

        // 处理编辑分类
        async handleEditCategory() {
            console.log('开始处理编辑分类:', this.editCategoryForm);

            if (!this.editCategoryForm.name.trim()) {
                this.showMessage('请输入分类名称', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const categoryData = {
                    name: this.editCategoryForm.name.trim(),
                    parent_id: this.editCategoryForm.parent_id ? parseInt(this.editCategoryForm.parent_id) : null
                };

                console.log('发送的分类数据:', categoryData);

                const response = await api.updateCategory(this.editCategoryForm.id, categoryData);

                if (response.code === 200) {
                    this.showMessage('分类修改成功！', 'success');
                    await this.loadInitialData();
                    this.closeEditCategoryModal();
                } else {
                    this.showMessage(response.message || '修改分类失败', 'error');
                }
            } catch (error) {
                console.error('修改分类失败:', error);
                this.showMessage('修改分类失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 删除分类
        async deleteCategory(categoryId) {
            if (!confirm('确定要删除这个分类吗？删除后该分类下的收藏将变为未分类。')) {
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.deleteCategory(categoryId);

                if (response.code === 200) {
                    this.showMessage('分类删除成功！', 'success');
                    // 重新加载所有数据以确保所有页面都更新
                    await this.loadInitialData();
                } else {
                    this.showMessage(response.message || '删除分类失败', 'error');
                }
            } catch (error) {
                console.error('删除分类失败:', error);
                this.showMessage('删除分类失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 编辑收藏
        editBookmark(bookmark) {
            this.editBookmarkForm = {
                id: bookmark.id,
                url: bookmark.url,
                title: bookmark.title,
                description: bookmark.description || '',
                category_id: bookmark.category_id || ''
            };
            this.showEditBookmarkModal = true;
        },

        // 处理编辑收藏
        async handleEditBookmark() {
            if (!this.editBookmarkForm.url.trim() || !this.editBookmarkForm.title.trim()) {
                this.showMessage('请填写网址和标题', 'warning');
                return;
            }

            if (!utils.validateURL(this.editBookmarkForm.url)) {
                this.showMessage('请输入有效的网址', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const bookmarkData = {
                    url: utils.formatURL(this.editBookmarkForm.url.trim()),
                    title: this.editBookmarkForm.title.trim(),
                    description: this.editBookmarkForm.description.trim(),
                    category_id: this.editBookmarkForm.category_id ? parseInt(this.editBookmarkForm.category_id) : null
                };

                const response = await api.updateBookmark(this.editBookmarkForm.id, bookmarkData);

                if (response.code === 200) {
                    this.showMessage('收藏修改成功！', 'success');
                    await this.loadInitialData();
                    this.closeEditBookmarkModal();
                } else {
                    this.showMessage(response.message || '修改收藏失败', 'error');
                }
            } catch (error) {
                console.error('修改收藏失败:', error);
                this.showMessage('修改收藏失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 处理编辑时的URL预览
        async handleEditUrlPreview() {
            if (!this.editBookmarkForm.url.trim()) {
                this.showMessage('请先输入网址', 'warning');
                return;
            }

            if (!utils.validateURL(this.editBookmarkForm.url)) {
                this.showMessage('请输入有效的网址', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.getURLPreview(this.editBookmarkForm.url);

                if (response.code === 200 && response.data) {
                    if (response.data.title) {
                        this.editBookmarkForm.title = response.data.title;
                    }
                    if (response.data.description) {
                        this.editBookmarkForm.description = response.data.description;
                    }
                    this.showMessage('预览获取成功！', 'success');
                } else {
                    this.showMessage('无法获取网址预览，请手动填写标题', 'warning');
                }
            } catch (error) {
                console.error('获取预览失败:', error);
                this.showMessage('获取预览失败，请手动填写标题', 'warning');
            } finally {
                this.isLoading = false;
            }
        },

        // 删除收藏
        async deleteBookmark(bookmarkId) {
            if (!confirm('确定要删除这个收藏吗？')) {
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.deleteBookmark(bookmarkId);

                if (response.code === 200) {
                    this.showMessage('收藏删除成功！', 'success');
                    // 重新加载所有数据以确保首页计数器也更新
                    await this.loadInitialData();
                } else {
                    this.showMessage(response.message || '删除收藏失败', 'error');
                }
            } catch (error) {
                console.error('删除收藏失败:', error);
                this.showMessage('删除收藏失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },







        // 获取可用的父分类（排除自己和子分类，避免循环引用）
        getAvailableParentCategories(excludeId) {
            if (!excludeId) return this.categoryTree;

            const filterTree = (tree) => {
                return tree.filter(category => {
                    if (category.id === excludeId) return false;

                    // 排除当前分类的所有后代（避免形成环）
                    const isDescendant = this.isDescendantOf(category, excludeId);
                    if (isDescendant) return false;

                    // 过滤子分类
                    if (category.children && category.children.length > 0) {
                        category.children = filterTree(category.children);
                    }

                    return true;
                });
            };

            return filterTree(JSON.parse(JSON.stringify(this.categoryTree)));
        },

        // 在分类树中查找指定ID的节点
        findCategoryInTree(tree, id) {
            for (const node of tree) {
                if (node.id === id) return node;
                if (node.children && node.children.length > 0) {
                    const found = this.findCategoryInTree(node.children, id);
                    if (found) return found;
                }
            }
            return null;
        },

        // 检查category是否是ancestorId的后代
        // 正确逻辑：从ancestorId对应节点向下查找是否包含category.id
        isDescendantOf(category, ancestorId) {
            const ancestorNode = this.findCategoryInTree(this.categoryTree, ancestorId);
            if (!ancestorNode) return false;

            const contains = (node, targetId) => {
                if (!node.children || node.children.length === 0) return false;
                for (const child of node.children) {
                    if (child.id === targetId) return true;
                    if (contains(child, targetId)) return true;
                }
                return false;
            };

            return contains(ancestorNode, category.id);
        },

        // 处理编辑个人信息（支持部分更新）
        async handleEditProfile() {
            // 构建只包含有值字段的更新数据
            const profileData = {};

            // 检查用户名
            if (this.editProfileForm.username.trim()) {
                if (this.editProfileForm.username.trim().length < 3) {
                    this.showMessage('用户名至少需要3个字符', 'warning');
                    return;
                }
                profileData.username = this.editProfileForm.username.trim();
            }

            // 检查邮箱
            if (this.editProfileForm.email.trim()) {
                if (!utils.validateEmail(this.editProfileForm.email)) {
                    this.showMessage('请输入有效的邮箱地址', 'warning');
                    return;
                }
                profileData.email = this.editProfileForm.email.trim();
            }

            // 检查密码
            if (this.editProfileForm.password.trim()) {
                if (this.editProfileForm.password.trim().length < 6) {
                    this.showMessage('密码至少需要6个字符', 'warning');
                    return;
                }
                profileData.password = this.editProfileForm.password.trim();
            }

            // 检查是否有字段需要更新
            if (Object.keys(profileData).length === 0) {
                this.showMessage('请至少填写一个要修改的字段', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                console.log('发送个人信息更新请求:', profileData);

                const response = await api.updateUserProfile(this.user.id, profileData);

                if (response.code === 200) {
                    this.showMessage('个人信息修改成功！', 'success');

                    // 关闭编辑模态框
                    this.closeEditProfileModal();

                    // 先结束加载状态，然后在后台刷新用户数据
                    this.isLoading = false;

                    // 重新获取最新的用户数据以确保数据一致性（不显示加载状态）
                    console.log('个人信息修改成功，重新获取最新用户数据');
                    this.refreshUserDataAfterEdit(); // 不使用await，让它在后台执行
                    return; // 提前返回，避免执行finally块
                } else {
                    this.showMessage(response.message || '修改个人信息失败', 'error');
                }
            } catch (error) {
                console.error('修改个人信息失败:', error);
                this.showMessage('修改个人信息失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 获取总访问量
        getTotalVisits() {
            return this.bookmarks.reduce((total, bookmark) => {
                return total + (bookmark.visit_count || 0);
            }, 0);
        },

        // 批量操作相关方法
        // 进入批量操作模式
        enterBatchMode() {
            this.batchMode = true;
            this.selectedBookmarks = [];
        },

        // 退出批量操作模式
        exitBatchMode() {
            this.batchMode = false;
            this.selectedBookmarks = [];
        },

        // 全选收藏
        selectAllBookmarks() {
            this.selectedBookmarks = this.filteredBookmarks.map(bookmark => bookmark.id);
        },

        // 清空选择
        clearSelection() {
            this.selectedBookmarks = [];
        },

        // 批量删除收藏
        async batchDeleteBookmarks() {
            if (this.selectedBookmarks.length === 0) {
                this.showMessage('请先选择要删除的收藏', 'warning');
                return;
            }

            const confirmed = confirm(`确定要删除选中的 ${this.selectedBookmarks.length} 个收藏吗？此操作不可撤销。`);
            if (!confirmed) return;

            try {
                this.isLoading = true;
                const response = await api.batchOperateBookmarksAsync({
                    bookmark_ids: this.selectedBookmarks,
                    action: 'delete'
                });

                if (response.code === 200) {
                    this.showMessage(`成功删除 ${this.selectedBookmarks.length} 个收藏`, 'success');
                    // 重新加载收藏数据
                    await this.loadBookmarks();
                    // 退出批量操作模式
                    this.exitBatchMode();
                } else {
                    this.showMessage(response.message || '批量删除失败', 'error');
                }
            } catch (error) {
                console.error('批量删除失败:', error);
                this.showMessage('批量删除失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 打开批量移动模态框
        openBatchMoveModal() {
            if (this.selectedBookmarks.length === 0) {
                this.showMessage('请先选择要移动的收藏', 'warning');
                return;
            }
            this.showBatchMoveModal = true;
        },

        // 关闭批量移动模态框
        closeBatchMoveModal() {
            this.showBatchMoveModal = false;
            this.batchMoveForm.target_category_id = '';
        },

        // 处理批量移动
        async handleBatchMove() {
            if (this.selectedBookmarks.length === 0) {
                this.showMessage('请先选择要移动的收藏', 'warning');
                return;
            }

            try {
                this.isLoading = true;
                const response = await api.batchOperateBookmarksAsync({
                    bookmark_ids: this.selectedBookmarks,
                    action: 'move',
                    category_id: this.batchMoveForm.target_category_id ? parseInt(this.batchMoveForm.target_category_id) : null
                });

                if (response.code === 200) {
                    const targetCategoryName = this.batchMoveForm.target_category_id
                        ? this.getCategoryName(parseInt(this.batchMoveForm.target_category_id))
                        : '未分类';
                    this.showMessage(`成功将 ${this.selectedBookmarks.length} 个收藏移动到 ${targetCategoryName}`, 'success');

                    // 重新加载收藏数据
                    await this.loadBookmarks();
                    // 关闭模态框并退出批量操作模式
                    this.closeBatchMoveModal();
                    this.exitBatchMode();
                } else {
                    this.showMessage(response.message || '批量移动失败', 'error');
                }
            } catch (error) {
                console.error('批量移动失败:', error);
                this.showMessage('批量移动失败，请检查网络连接', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 生成最近活动数据
        generateRecentActivities() {
            const activities = [];

            // 最近创建的收藏
            const recentBookmarks = this.bookmarks
                .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
                .slice(0, 3);

            recentBookmarks.forEach(bookmark => {
                activities.push({
                    id: `bookmark-${bookmark.id}`,
                    icon: '⭐',
                    text: `添加了收藏：${bookmark.title}`,
                    time: bookmark.created_at
                });
            });

            // 最近创建的分类
            const recentCategories = this.categories
                .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
                .slice(0, 2);

            recentCategories.forEach(category => {
                activities.push({
                    id: `category-${category.id}`,
                    icon: '📁',
                    text: `创建了分类：${category.name}`,
                    time: category.created_at
                });
            });

            // 按时间排序
            this.recentActivities = activities
                .sort((a, b) => new Date(b.time) - new Date(a.time))
                .slice(0, 5);
        },







        // 查找分类（递归搜索）
        findCategoryById(categoryId) {
            const findInTree = (tree) => {
                for (const category of tree) {
                    if (category.id === parseInt(categoryId)) {
                        return category;
                    }
                    if (category.children && category.children.length > 0) {
                        const found = findInTree(category.children);
                        if (found) return found;
                    }
                }
                return null;
            };

            return findInTree(this.categoryTree) || this.categories.find(cat => cat.id === parseInt(categoryId));
        },

        // ==================== 诊断方法 ====================

        // 诊断分类管理页面问题
        diagnoseCategoriesPage() {
            console.log('=== 分类管理页面诊断 ===');
            console.log('当前activeTab:', this.activeTab);
            console.log('categoryTree长度:', this.categoryTree.length);
            console.log('categories长度:', this.categories.length);
            console.log('expandedCategories:', this.expandedCategories);
            console.log('expandedBookmarkCategories:', this.expandedBookmarkCategories);
            console.log('hoveredTab:', this.hoveredTab);
            console.log('showBatchOperationPanel:', this.showBatchOperationPanel);
            console.log('selectedBookmarksCount:', this.selectedBookmarksCount);
            console.log('=== 诊断结束 ===');
        },


    },

    computed: {
        // 分类总数（包括所有层级）
        totalCategoriesCount() {
            return this.categories.length;
        },

        // 根分类（顶级技能）
        rootCategories() {
            return this.categories.filter(category => !category.parent_id);
        },

        // 过滤后的收藏列表
        filteredBookmarks() {
            let filtered = this.bookmarks;

            // 按分类筛选
            if (this.filterCategory) {
                filtered = filtered.filter(bookmark =>
                    bookmark.category_id === parseInt(this.filterCategory)
                );
            }

            // 按搜索关键词筛选
            if (this.searchQuery) {
                const query = this.searchQuery.toLowerCase();
                filtered = filtered.filter(bookmark =>
                    bookmark.title.toLowerCase().includes(query) ||
                    bookmark.description.toLowerCase().includes(query) ||
                    bookmark.url.toLowerCase().includes(query)
                );
            }

            return filtered;
        },


    },

    components: {
        TreeSelect,
        TreeSelectOption,
        CategoryManagementNode
    },

    provide() {
        return {
            getBookmarkCount: this.getCategoryBookmarkCount
        };
    }
};

// 创建Vue应用实例
const app = createApp(vueAppConfig);

// 添加全局错误处理器
app.config.errorHandler = (err, instance, info) => {
    console.error('Vue渲染错误:', err);
    console.error('错误信息:', info);
    console.error('组件实例:', instance);

    // 如果是分类管理相关的错误，提供更详细的诊断信息
    if (info.includes('render') || info.includes('categories')) {
        console.error('=== 分类管理错误诊断 ===');
        if (instance && instance.activeTab) {
            console.error('当前activeTab:', instance.activeTab);
        }
        if (instance && instance.categoryTree) {
            console.error('categoryTree长度:', instance.categoryTree.length);
        }
        if (instance && instance.expandedBookmarkCategories) {
            console.error('expandedBookmarkCategories类型:', typeof instance.expandedBookmarkCategories);
            console.error('expandedBookmarkCategories值:', instance.expandedBookmarkCategories);
        }
        if (instance && instance.selectedBookmarks) {
            console.error('selectedBookmarks类型:', typeof instance.selectedBookmarks);
            console.error('selectedBookmarks值:', instance.selectedBookmarks);
        }
    }
};

// 注册组件并挂载应用
app.component('TreeSelect', TreeSelect)
    .component('TreeSelectOption', TreeSelectOption)
    .component('CategoryManagementNode', CategoryManagementNode)
    .mount('#app');
